//
//  XiaoximenLoginViewController.m
//  Xiaoximen_iOS
//
//  Created by Wang Zhongyu on 12-7-17.
//  Copyright (c) 2012年 Peking University. All rights reserved.
//

#import "XiaoximenLoginViewController.h"
#import "ASIHTTPRequest.h"

@interface XiaoximenLoginViewController ()
{
	CGRect initWelFrame;
	CGRect initUsernameFrame;
	CGRect initPhoneFrame;
}

@end

@implementation XiaoximenLoginViewController
@synthesize welImage;
@synthesize usernameTextField;
@synthesize phoneTextField;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	
	initWelFrame = welImage.frame;
	initUsernameFrame = usernameTextField.frame;
	initPhoneFrame = phoneTextField.frame;
	
	UIView *usernamePaddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 18, 0)];
	usernameTextField.leftView = usernamePaddingView;
	usernameTextField.leftViewMode = UITextFieldViewModeAlways;
	UIView *phonePaddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 18, 0)];
	phoneTextField.leftView = phonePaddingView;
	phoneTextField.leftViewMode = UITextFieldViewModeAlways;
}

- (void)viewDidUnload
{
	[self setWelImage:nil];
	[self setUsernameTextField:nil];
	[self setPhoneTextField:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    if (!CGRectContainsPoint(self.usernameTextField.frame,[touch locationInView:self.view])) {
        if (!_isKeyboardHidden) {
            [self.usernameTextField resignFirstResponder];
        }
    }
	if (!CGRectContainsPoint(self.phoneTextField.frame,[touch locationInView:self.view])) {
        if (!_isKeyboardHidden) {
            [self.phoneTextField resignFirstResponder];
        }
    }
}
- (void)viewWillAppear:(BOOL)animated {
    // Register notifications for when the keyboard appears 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)keyboardWillShow:(NSNotification*)notification {
	_isKeyboardHidden = NO;
    [self moveViewForKeyboard:notification up:YES];
}

- (void)keyboardWillHide:(NSNotification*)notification {
	_isKeyboardHidden = YES;
    [self moveViewForKeyboard:notification up:NO];
}

- (void)moveViewForKeyboard:(NSNotification*)notification up:(BOOL)up {
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect keyboardRect;
	
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
	
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
	
	if (up == YES) {
        CGFloat keyboardHeight = keyboardRect.size.height;
        [welImage setFrame:CGRectMake(initWelFrame.origin.x, initWelFrame.origin.y-keyboardHeight+25, initWelFrame.size.width, initWelFrame.size.height)];
		[usernameTextField setFrame:CGRectMake(initUsernameFrame.origin.x, initUsernameFrame.origin.y-keyboardHeight+25, initUsernameFrame.size.width, initUsernameFrame.size.height)];
		[phoneTextField setFrame:CGRectMake(initPhoneFrame.origin.x, initPhoneFrame.origin.y-keyboardHeight+25, initPhoneFrame.size.width, initPhoneFrame.size.height)];
    } else {
		// Keyboard is going away (down) - restore original frame
        [welImage setFrame:initWelFrame];
		[usernameTextField setFrame:initUsernameFrame];
		[phoneTextField setFrame:initPhoneFrame];
    }
	
    [UIView commitAnimations];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == self.phoneTextField) {
		if ([self.usernameTextField.text length] <= 0) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"貌似没有发现姓名呢" message:nil delegate:nil cancelButtonTitle:@"再填一次^_^" otherButtonTitles:nil];
			[alert show];
			[self.usernameTextField becomeFirstResponder];
		} else if ([self.phoneTextField.text length] <= 0) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"好像没有找到手机呀" message:nil delegate:nil cancelButtonTitle:@"再买一只^_^" otherButtonTitles:nil];
			[alert show];
			[self.phoneTextField becomeFirstResponder];
		} else if ([self.phoneTextField.text length] != 11 || ![self.phoneTextField.text hasPrefix:@"1"]) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"手机号大概不对哦" message:nil delegate:nil cancelButtonTitle:@"让我改改^_^" otherButtonTitles:nil];
			[alert show];
			[self.phoneTextField becomeFirstResponder];
		} else {
			[self.phoneTextField resignFirstResponder];
			
			NSString *username = self.usernameTextField.text;
			NSString *phone = self.phoneTextField.text;
			NSString *urlString = [[NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/user/add?name=%@&cellphone=%@", username, phone] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
			NSLog(@"%@", urlString);
			NSURL *url = [NSURL URLWithString:urlString];
			ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
			[request setDelegate:self];
			[request startAsynchronous];
		}

		return NO;
    } else if (textField == self.usernameTextField) {
        [self.phoneTextField becomeFirstResponder];
    }
    return YES;
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
	// Use when fetching text data
	NSString *responseString = [request responseString];
	NSLog(@"%@", responseString);
	// Use when fetching binary data
	NSData *responseData = [request responseData];
	//NSLog(@"%@", responseData);
	// Use when fetching json data
	id res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONWritingPrettyPrinted error:nil];
	NSLog(@"%@", res);
	
	[[NSUserDefaults standardUserDefaults] setValue:self.usernameTextField.text forKey:@"user_name"];
	[[NSUserDefaults standardUserDefaults] setValue:self.phoneTextField.text forKey:@"user_cellphone"];
	[[NSUserDefaults standardUserDefaults] setValue:[res objectForKey:@"user_id"] forKey:@"user_id"];
	[self dismissModalViewControllerAnimated:YES];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	NSError *error = [request error];
	NSLog(@"%@", error);
	[self performSegueWithIdentifier:@"ErrorSegue" sender:self];
}

@end
